<template>
  <CustomNav title="微信登录"></CustomNav>
  <view class="">
    <view class="content">
      <view class="logo">
        <view class="img">
          <image src="/static/logo.jpg" mode=""></image>
        </view>
        <view class="title">陕西工业职业技术大学</view>
      </view>
      <view class="btn_box_wx">
        <!-- 在这里添加遮罩层的原因：由于点击button会立刻触发open-type调用，无法在点击前做出相应的逻辑判断 -->
        <!-- 当isAgree（同意协议）遮罩层隐藏 -->
        <view class="mask" @click="handleLogin" v-if="!isAgree"></view>
        <button
          class="btn wx"
          open-type="getPhoneNumber"
          @getphonenumber="getPhoneNumber"
        >
          一键登录
        </button>
        <!-- <button open-type="contact" @contact="handleContact">客服</button> -->
        <!-- <view class="btn white">
          取消授权
        </view> -->
      </view>
    </view>
  </view>

  <view class="agree_container">
    <view class="animation-container" :class="isAnmation ? 'animation' : ''">
      <label for="radio" class="foot">
        <checkbox-group class="agree" @change="handleAgree">
          <checkbox :checked="isAgree" id="radio" />
        </checkbox-group>
      </label>
      <view class="right">
        <text
          style="margin-left: 5rpx; font-size: 26rpx"
          @click="isAgree = !isAgree"
          >我已阅读并同意</text
        >
        <text class="text" @click="userAgreement">《用户协议》</text> 和
        <text @click="privacyAgreement" class="privacyAgreement"
          >《隐私协议》</text
        >
      </view>
    </view>
  </view>
</template>

<script setup>
// import { wxLogin } from "@/api/login";
import { getItem, setItem, updateItem } from "@/utils/localStorage";
import { Alert, unAlert } from "@/utils/tool";
// import useWxUserStore from "@/store/modules/wxUser";
import CustomNav from "@/components/CustomNav/index.vue";
import { wxLogin, userInfo } from "@/api/login";
import useUserStore from "@/store/modules/user";
import env from "@/utils/env";

const userStore = useUserStore();

const code = ref("");
const isAgree = ref(false); // wx是否同意协议
const isAnmation = ref(false); // 是否播放动画

// 校区
const campus = ref("");
let itemList = ["新校区", "旧校区"]; // 旧校区0    新校区1
// 只显示当前校区的订单
const handleLogin = () => {
  // 播放动画
  isAnmation.value = true;
  setTimeout(() => {
    // 清除动画（下次可继续播放）
    isAnmation.value = false;
  }, 500);
  if (!isAgree.value) {
    // 未同意协议
    Alert("请同意用户协议与隐私政策", "none", 1000);
  }
};

const handleAgree = (e) => {
  // 是否同意协议（wx小程序）
  isAgree.value = !isAgree.value;
};

// ****************************微信手机号登录**************************************
// 获取手机号
const getPhoneNumber = async (e) => {
  // 1. 拿到code
  const code = e.detail.code;
  // 将code传给后端，后端拿这个code能达到openid（注：小程序中获取手机号时返回的 code 和 wx.login API 返回的 code 不一样）
  const openIdCode = await wx.login();

  console.log("code:", code);
  console.log("openIdCode:", code);
  // 保证用户点击了允许
  if (e.detail.encryptedData || e.detail.iv) {
    // try 代表请求发送成功了，但里面想要的结果错不错就不知道了
    try {
      Alert("登录中...", "loading", 0, true);

      // console.log("openIdCode:", openIdCode);

      const result = await wxLogin({
        code: code,
        openIdCode: openIdCode.code,
      });
      // const result = await wxLogin();

      console.log("result：", result);

      result.data.data.user.headPath = `${env.baseUrl}/studio/img/head/${result.data.data.user.headPath}`;

      if (result.data.code == 200) {
        userStore.updateUserInfo(result.data.data.token, result.data.data.user);

        Alert("登录成功", "success");

        setTimeout(() => {
          // 跳转到首页（逻辑在updateUserInfo里）
          uni.reLaunch({ url: "/pages/index/index" });
        }, 1000);
      } else {
        Alert("登录失败", "error", 1000);
      }

      // 2. 发请求，将code传给后端
      // const res = await wxLogin({
      //   wxCode: code,
      //   openIdCode: openIdCode.code,
      // });

      // console.log("res：", res);

      // if (res.data.code == 200) {
      //   wxUserStore.updateUserInfo(res.data.data, res.data.token);

      //   // unAlert()

      //   // 跳转到首页（逻辑在updateUserInfo里）
      //   // uni.switchTab({ url: '/pages/index/index' })

      //   // 将isShowApplyOrder该为-1   表示不显示申请接单
      //   if (res.data.data.studentIsApply == 2) {
      //     setItem("isShowApplyOrder", -1);
      //     console.log("审核通过了");
      //   }
      // } else {
      //   Alert("登录失败", "error", 1000);
      // }
    } catch {
      // 表示后端服务器有问题（比如服务器挂了）
      Alert("服务异常", "error", 1000);
    }

    // 3. 结果
  } else {
    // Alert('登录失败')
  }
};

// 用户协议
const userAgreement = () => {
  uni.navigateTo({
    url: "/pagesC/userAgreement/index",
  });
};
// 隐私协议
const privacyAgreement = () => {
  uni.navigateTo({
    url: "/pagesC/privacyAgreement/index",
  });
};
</script>

<style lang="scss">
// wx
.logo {
  margin-top: 300rpx;

  .img {
    margin: 0 auto;
    width: 150rpx;
    height: 150rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .title {
    text-align: center;
    margin-top: 20rpx;
  }
}

.btn_box_wx {
  width: 580rpx;
  margin: 0 auto;
  margin-top: 100rpx;
  position: relative;

  .mask {
    width: 750rpx;
    height: 500rpx;
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    z-index: 10;
    // background-color: rgba(43, 78, 125, .3);
    top: -106rpx;
  }

  .btn {
    text-align: center;
    border-radius: 10rpx;
    line-height: 2.8;

    // 按下
    &:active {
      // background-color: #60ca88a1;
      background-color: #2d6ef185;
    }
  }

  // button
  .wx {
    color: #fff;
    // background-color: #60ca88;
    background-color: #2d6ef1;
  }

  .white {
    font-size: 24rpx;
    color: #555;
  }
}

.agree_container {
  width: 750rpx;
  position: fixed;
  bottom: 50rpx;
  left: 50%;
  transform: translateX(-50%);

  .animation-container {
    display: flex;
    align-items: center;
    font-size: 22rpx;
    justify-content: center;

    &.animation {
      animation: agree 0.5s linear;
    }

    .foot {
      .agree {
        transform: scale(0.7) translate(12rpx, -1rpx);
      }
    }

    .right {
      font-size: 26rpx;

      .text {
        color: #4992ff;
        font-weight: 900;
        font-size: 26rpx;
      }

      .privacyAgreement {
        color: #4992ff;
        font-weight: 900;
        font-size: 26rpx;
      }
    }
  }
}

// 未同意协议动画
@keyframes agree {
  0% {
    transform: translateX(-5%);
  }

  20% {
    transform: translateX(5%);
  }

  40% {
    transform: translateX(-5%);
  }

  60% {
    transform: translateX(5%);
  }

  80% {
    transform: translateX(-5%);
  }

  100% {
    transform: translateX(0%);
  }
}
</style>
